/* components */
import { ConnectorModuleCardItem } from '@src/modules/connector/components'
/* model */
import { ConnectorModuleComponentNameEnum } from '@src/modules/connector/model'
/* scss */
import '@src/modules/connector/view/list/components/card/item.scss'
/* vue */
import { CreateElement, ComponentInstance, ComponentRenderProxy, defineComponent, PropType, getCurrentInstance } from 'vue'
import { CommonComponentInstance } from '@model/VC'
/* types */
import { ConnectorSettingCardItem } from '@src/modules/connector/types'
/* util */
import { isOpenData } from '@src/util/platform'
import { fmt_datetime } from '@src/filter/fmt'
import { message } from '@src/util/message'
import { t } from '@src/locales'
import { postPage } from 'pub-bbx-utils'
/* api */
import * as TriggerApi from '@src/modules/connector/api/trigger'
/* components */
import { Notification, Button } from 'element-ui'

export type ConnectorListViewCardItemProps = {
  value: ConnectorSettingCardItem;
}

export interface ConnectorListViewCardItemSetupState {
  
}

export enum ConnectorListViewCardItemEmitEventNameEnum {
  Input = 'input',
  Update = 'update',
  Edit = 'edit',
  Delete = 'delete',
  UpdateState = 'updateState',
  Log = 'log'
}

export type ConnectorListViewCardItemInstance = ComponentInstance & ConnectorListViewCardItemSetupState
export type ConnectorListViewCardItemVM = ComponentRenderProxy<ConnectorListViewCardItemProps> & CommonComponentInstance & ConnectorListViewCardItemInstance

export default defineComponent({
  name: ConnectorModuleComponentNameEnum.ConnectorListViewCardItem,
  emits: [
    ConnectorListViewCardItemEmitEventNameEnum.Input,
    ConnectorListViewCardItemEmitEventNameEnum.Update,
    ConnectorListViewCardItemEmitEventNameEnum.Edit,
    ConnectorListViewCardItemEmitEventNameEnum.Delete,
    ConnectorListViewCardItemEmitEventNameEnum.Log,
  ],
  props: {
    value: {
      type: Object as PropType<ConnectorSettingCardItem>,
    },
    edit: {
      type: Boolean,
      default: false,
    },
    delete: {
      type: Boolean,
      default: false,
    }
  },
  setup(props: ConnectorListViewCardItemProps, { emit }) {
    const instance = getCurrentInstance()
    const onUpdateHandler = () => {
      emit(ConnectorListViewCardItemEmitEventNameEnum.Update, props.value)
    }
    
    const onEditHandler = () => {
      emit(ConnectorListViewCardItemEmitEventNameEnum.Edit, props.value)
    }
    
    const onDeleteHandler = () => {
      emit(ConnectorListViewCardItemEmitEventNameEnum.Delete, props.value)
    }

    const onLogListHandler = () => {
      emit(ConnectorListViewCardItemEmitEventNameEnum.Log, props.value)
    }
    
    
    const updateState = (val:number) => {
      if (!props.edit) {
        return
      }
      TriggerApi.updateTriggerStat({triggerId:props.value.id, enable:val}).then((res:any)=>{
        if(res.status == 0){
          emit(ConnectorListViewCardItemEmitEventNameEnum.UpdateState, val)
          
          if (val === 1) {
            message.success(t('trigger.button.enableSuccess'))
          } else if (val === 0) {
            message.success(t('trigger.button.disableSuccess'))
          }
        } else if (res.status === 20001) {
          dosageNotification({used: res.data.used, total: res.data.total})
        } else{
          message.error(res.message)
        }
      })
    }

    const dosageNotification = ({used= 0, total= 0}) => {
      const h = instance?.proxy.$createElement
			Notification({
				customClass: 'isEnable-notification',
				type: 'info',
				title: t("trigger.tip.text1"),
				duration: 0,
				message: h('div', [
					h('p', { style: { marginTop: '16px' } }, `${t("trigger.tip.text2")} ${used}/${total}`),
					h('p', { style: { marginBottom: '16px' } }, t("trigger.tip.text3")),
					h(Button, {
						props: { type: 'primary' },
            on: { click: jumpContactUs }
					}, t("trigger.tip.text4"))
				]),
			});
		}

		const jumpContactUs = () => {
			postPage({
        action: 'shb.system.openChat',
        data: {}
      })
    }

    return {
      onUpdateHandler,
      onEditHandler,
      onDeleteHandler,
      updateState,
      onLogListHandler
    }
    
  },
  computed: {
    triggerProcessVO() {
      return this.value?.triggerProcessVOList?.[0] || {}
    },
    fromAppLogo() {
      return this.triggerProcessVO?.from?.icon || ''
    },
    toAppLogo() {
      return this.triggerProcessVO?.to?.icon || ''
    },
  },
  render(h: CreateElement) {
    return (
      <ConnectorModuleCardItem class={ConnectorModuleComponentNameEnum.ConnectorListViewCardItem}>
        
        <div class="connector-list-view-card-item-content">
          
          <div class="connector-list-view-card-item-header">
            
            <div class="connector-list-view-card-item-name">
              { this.value.triggerName }
            </div>
            
            <div class="connector-list-view-card-item-switch">
              {
                this.edit ? (
                  <el-switch
                    disabled={!this.edit}
                    active-value={1}
                    inactive-value={0}
                    value={this.value.enable}
                    onChange={this.updateState}
                    >
                  </el-switch>  
                ): (
                  <el-tooltip class="item" effect="dark" content={t('trigger.isAuth')}  placement="top-start">
                    <el-switch
                       disabled={this.edit}
                       active-value={1}
                       inactive-value={0}
                       value={this.value.enable}
                       onChange={this.updateState}
                     >
                    </el-switch>
                  </el-tooltip>
                )
              }
            </div>
          </div>
          
          <div class="connector-list-view-card-item-description">
            { this.value.triggerDesc }
          </div>
{/*           
          {this.value.triggerProcessVOList?.[0] ? (
            <div class="connector-list-view-card-item-module">

              <span>
                { this.fromAppLogo.startsWith('http') ? (<img class="module-logo" src={this.fromAppLogo}></img>) : (<i class={['iconfont', 'app-logo', this.fromAppLogo]} />)}
                { this.value.triggerProcessVOList[0].from.bizTypeName }
              </span>

              <i class="iconfont icon-arrow-left">
              </i>

              <span>
                { this.toAppLogo.startsWith('http') ? (<img class="module-logo" src={this.toAppLogo}></img>) : (<i class={['iconfont', 'app-logo', this.toAppLogo]} />)}
                { this.value.triggerProcessVOList[0].to.bizTypeName }
              </span>

            </div>
          ) : ''} */}
          
          <div class="connector-list-view-card-item-type">
            { t('common.connector.trigger.no') }：{ this.value.triggerNo }
          </div>

          <div class="connector-list-view-card-item-update">

            { t('common.base.lastUpdate') }：

            {isOpenData ? (
              <open-data type="userName" openid={this.value.operatorStaffId}>
              </open-data>
            ) : (
              this.value.operatorName
            )}
            
            <span class="connector-list-view-card-item-update-time">
              { fmt_datetime(this.value.updateTime) }
            </span>
            
          </div>
          
          {/*
          <div class="connector-list-view-card-item-action">
            执行动作：{ this.value.action }
          </div> */}

        </div>
        
        <div class="connector-list-view-card-item-footer-left" slot="footerLeft">
          <el-dropdown placement="top">
            
            <i class="icon-diandiandian iconfont">{t('common.base.moreOperator')}</i>
            
            <el-dropdown-menu slot="dropdown">
              
              <el-dropdown-item>
                <div onClick={this.onUpdateHandler} v-show={this.edit}>
                  <i class="iconfont icon-edit-square"></i>
                  {t('common.base.rename')}
                </div>
              </el-dropdown-item>
              
              <el-dropdown-item>
                <div onClick={this.onDeleteHandler} v-show={this.delete}>
                  <i class="iconfont icon-delete"></i>
                  {t('common.base.delete')}
                </div>
              </el-dropdown-item>

              <el-dropdown-item>
                <div onClick={this.onLogListHandler}>
                  <i class="iconfont icon-wendang"></i>
                  {t('common.pageTitle.pageCallLog')}
                </div>
              </el-dropdown-item>
              
            </el-dropdown-menu>
            
          </el-dropdown>
        </div>
        
        <div class="connector-list-view-card-item-footer-right" slot="footerRight" v-show={this.edit}>
          <div slot="footerRight">
            <i 
              class="icon-edit-square iconfont" 
              onClick={this.onEditHandler}
            >
              {t('common.base.edit')}
            </i>
          </div>
        </div>
        
      </ConnectorModuleCardItem>
    )
  }
})
